<?php

namespace App;

use Aws\Laravel\AwsFacade;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;

class MinIo
{

    /**
     * @var \Aws\AwsClientInterface
     */
    private $client;

    private $bucket;


    public function __construct()
    {
        $this->client = AwsFacade::createClient("s3");
        $this->bucket = config("aws.bucket");
    }

    /**
     * @param Request $request
     * @param string $fileKey
     * @return array
     * @throws \Exception
     */
    public function requestUpload(Request $request, string $fileKey): array
    {
        $res = [];
//        dd($request->file($fileKey));
        if (!$request->hasFile($fileKey)) {
            throw new \Exception("上传文件不存在");
        }
        $files = $request->file($fileKey);
        if (!is_array($files)) {
            $files = [$files];
        }
        $toPath = date("Y/m/d/");
        foreach ($files as $v) {

            $res[] = $this->upload($v, $toPath);
        }

        return $res;
    }

    /**
     * @param UploadedFile $file
     * @param string $toPath
     * @param string $fileName
     * @return array
     * @throws \Exception
     */
    public function upload(UploadedFile $file, string $toPath, string $fileName = ""): array
    {
        $fileName = $fileName ?: $file->getClientOriginalName();
        $pathName = $toPath . md5($fileName) . "." . $file->getClientOriginalExtension();
        $res = $this->client->putObject(array(
            'Bucket' => $this->bucket,
            'Key' => $pathName,
            'SourceFile' => $file->getRealPath(),
        ));
        if ($res["@metadata"]["statusCode"] != 200) {
            throw new \Exception("上传失败");
        }
        return compact('fileName', 'pathName');
    }

    /**
     * @param string $pathName
     * @param int $min
     * @return string
     */
    public function getUrl(string $pathName, int $min = 10): string
    {
        $command = $this->client->getCommand('GetObject', [
            'Bucket' => $this->bucket,
            'Key' => $pathName,
        ]);

        //获得一个10分钟有效期的pre-signed URL
        $request = $this->client->createPresignedRequest($command, '+' . $min . ' minutes');

        //获得url
        return (string)$request->getUri();

    }
}
